<template>
  <van-form @submit="onSubmit">
    <template v-if="editUser.editKey!=='userAvatar'">
      <van-cell-group inset>
        <van-field
            v-model="editUser.currentKey"
            :name="editUser.editKey"
            :label="editUser.editName"
            :placeholder="`请输入${editUser.editName}`"
        />
      </van-cell-group>
    </template>
    <template v-if="editUser.editKey==='userAvatar'">
      <van-uploader :after-read="afterRead" />
    </template>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>

</template>

<script setup lang="ts">
import {useRoute,useRouter} from "vue-router";
import {ref} from "vue";
import myAxios from "../plugins/myAxios.js";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../services/user";

const route = useRoute();
const router = useRouter();

/**
 * 定义一个响应式对象
 * 不可以这么写，不是响应式的
v-model="route.query.currentKey"
:name="route.query.editKey"
:label="route.query.editName"
:placeholder="`请输入${route.query.editName}`" />
 */
const editUser=ref({
  editKey:route.query.editKey,
  currentKey: route.query.currentKey,
  editName:route.query.editName
}
)


//提交修改用户信息
const onSubmit =async () => {
  //获取当前用户信息（每次获取最新用户信息）
  const loginUser=await getCurrentUser()
  //判断用户是否登录
  if (!loginUser){
    showFailToast('用户未登录!')
    return
  }

  //前端向后端发请求
    const res= await myAxios.post('/user/update',{
      'id':loginUser.id,
      //js可以这么写 也就相当于 '属性':值
      [editUser.value.editKey as string]:editUser.value.currentKey
    })
  if (res.code===0 && res.data>0){
    showSuccessToast('修改成功')
    //返回上一级
    router.back()
  }else {
    showFailToast('修改失败,'+res.message)
  }
};

//上传头像
const afterRead = (file) => {
  // 此时可以自行将文件上传至服务器
  console.log('上传头像',file);
};
</script>

<style scoped>

</style>